package com.xxx.lib.ui

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.tencent.smtt.sdk.CookieManager
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.xxx.lib.AppConfig
import com.xxx.lib.InfoConfig
import com.xxx.lib.SPConfig
import com.xxx.lib.base.BaseActivity
import com.xxx.lib.databinding.ActivityWebViewBinding
import com.xxx.lib.utils.WebViewUtils


/**
 * 通用WebView
 */
class WebViewActivity : BaseActivity() {
    companion object {
        /**
         * 调试信息输出TAG
         */
        private const val TAG = "WebView"

        /**
         * 传递：标题
         */
        private const val EXTRA_TITLE = "extra_title"

        /**
         * 传递：链接
         */
        private const val EXTRA_LINK = "extra_link"

        /**
         * 传递：文本
         */
        private const val EXTRA_TEXT = "extra_text"

        /**
         * 加载链接
         * @param context Context实例
         * @param link 链接
         * @param title 标题，不传默认为 “”
         */
        fun startLoadLink(context: Context, link: String, title: String = "") {
            val intent = Intent(context, WebViewActivity::class.java).apply {
                putExtra(EXTRA_TITLE, title)
                putExtra(EXTRA_LINK, link)
            }
            context.startActivity(intent)
        }

        /**
         * 加载富文本
         * @param context Context实例
         * @param text 富文本
         * @param title 标题，不传默认为 “”
         */
        fun startLoadText(context: Context, text: String, title: String = "") {
            val intent = Intent(context, WebViewActivity::class.java).apply {
                putExtra(EXTRA_TITLE, title)
                putExtra(EXTRA_TEXT, text)
            }
            context.startActivity(intent)
        }

    }

    private val webView by lazy {
        WebView(this).apply {
            settings.setGeolocationEnabled(true)//允许定位
            webViewClient = mWebViewClient
            webChromeClient = mWebChromeClient
            val params = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            layoutParams = params
        }.also {
            binding.llLinearLayout.addView(it)
        }
    }

    private val binding by lazy { ActivityWebViewBinding.inflate(layoutInflater) }

    override fun initContentView(): View? = binding.root

    override fun init() {
        //标题
        val title = intent.getStringExtra(EXTRA_TITLE) ?: ""
        //链接（链接、富文本，两者传一）
        val link = intent.getStringExtra(EXTRA_LINK) ?: ""
        //富文本（链接、富文本，两者传一）
        val text = intent.getStringExtra(EXTRA_TEXT) ?: ""

        setTitle(title)
        setCookie(link)//设置Cookie
        when {
            link.isNotBlank() -> {
                webView.loadUrl(link)
            }
            text.isNotBlank() -> {
                webView.loadDataWithBaseURL(
                    AppConfig.appHost,
                    WebViewUtils.screenAdapter(text),
                    "text/html; charset=UTF-8",
                    null,
                    null
                )
            }
        }
    }

    /**
     * 设置Cookie
     * @param link 需要设置Cookie链接
     */
    private fun setCookie(link: String?) {
        if (link.isNullOrBlank()) return
        CookieManager.getInstance().run {
            setAcceptCookie(true)
            removeSessionCookies(null)
            removeAllCookies(null)
            setCookie(link, "token=${SPConfig.token}")//token
            setCookie(link, "deviceName=${InfoConfig.deviceName}")//设备名称
            setCookie(link, "osName=${InfoConfig.osName}")//系统名称
            setCookie(link, "osVersion=${InfoConfig.osVersion}")//系统版本
            setCookie(link, "appVersionName=${InfoConfig.appVersionName}")//应用版本名称
            setCookie(link, "appVersionCode=${InfoConfig.appVersionCode}")//应用版本号码
            flush()
        }
    }

    private val mWebViewClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView, link: String, favicon: Bitmap?) {
            super.onPageStarted(view, link, favicon)
            binding.progressBar.visibility = View.VISIBLE
        }

        override fun onPageFinished(view: WebView, link: String) {
            super.onPageFinished(view, link)
            if (!view.title.isNullOrBlank() && view.title != "about:blank") title = view.title
            binding.progressBar.visibility = View.INVISIBLE
            //调试模式下，输出链接
            if (AppConfig.isDebuggable) Log.i(TAG, "link=${link}")
        }
    }


    private val mWebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            binding.progressBar.progress = newProgress
        }
    }

    override fun onStart() {
        super.onStart()
        webView.settings.javaScriptEnabled = true
    }

    override fun onResume() {
        super.onResume()
        webView.onResume()
    }

    override fun onPause() {
        super.onPause()
        webView.onPause()
    }

    override fun onStop() {
        super.onStop()
        webView.settings.javaScriptEnabled = false
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.llLinearLayout.removeView(webView)
        webView.loadDataWithBaseURL(null, "", "text/html; charset=UTF-8", null, null)
        webView.clearHistory()
        webView.destroy()
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) webView.goBack() else super.onBackPressed()
    }
}